﻿//https://leetcode.cn/problems/diameter-of-binary-tree/?envType=study-plan-v2&envId=top-100-liked

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ans = 1;
    int height(TreeNode* root)
    {
        if (root == nullptr)
            return 0;

        int lheight = height(root->left);
        int rheight = height(root->right);
        ans = max(ans, lheight + rheight + 1);  //以某个节点为根节点经过的最大节点数
        return max(lheight, rheight) + 1;  //最大深度
    }
    int diameterOfBinaryTree(TreeNode* root) {
        height(root);
        return ans - 1;   //路径=经过的节点数-1
    }
};